package com.ysq.www.api.front.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysq.www.api.front.entity.Information;
import com.ysq.www.api.front.entity.InformationTag;
import com.ysq.www.api.front.entity.InformationTagMiddle;
import com.ysq.www.api.front.mapper.InformationMapper;
import com.ysq.www.api.front.mapper.InformationTagMapper;
import com.ysq.www.api.front.mapper.InformationTagMiddleMapper;
import com.ysq.www.api.front.service.IInformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysq.www.api.user.entity.Collect;
import com.ysq.www.api.user.entity.GiveLike;
import com.ysq.www.api.user.entity.User;
import com.ysq.www.api.user.mapper.CollectMapper;
import com.ysq.www.api.user.mapper.GiveLikeMapper;
import com.ysq.www.api.user.mapper.UserMapper;
import com.ysq.www.api.work.entity.Approve;
import com.ysq.www.api.work.entity.CopyTo;
import com.ysq.www.api.work.mapper.ApproveMapper;
import com.ysq.www.api.work.mapper.CopyToMapper;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.utils.Comm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 资讯表 服务实现类
 * </p>
 *
 * @author dql
 * @since 2020-08-07
 */
@Service
public class InformationServiceImpl extends ServiceImpl<InformationMapper, Information> implements IInformationService {

    @Autowired
    private InformationMapper informationMapper;

    @Autowired
    private ApproveMapper approveMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CopyToMapper copyToMapper;

    @Autowired
    private InformationTagMiddleMapper itmMapper;

    @Autowired
    private InformationTagMapper itMapper;

    @Autowired
    private GiveLikeMapper giveLikeMapper;

    @Autowired
    private CollectMapper collectMapper;

    /**
     * 首页分页查询最新资讯
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param userId 用户id
     * @param asId 协会id
     * @return IPage
     */
    @Override
    public IPage<Information> searchByPage(int pageNumber, int pageSize, Integer userId, Integer asId) {
        Page<Information> page = new Page<>(pageNumber,pageSize);
        IPage<Information> iPage = informationMapper.searchByPage(page,asId);
        List<Information> iList = iPage.getRecords();
        for (Information imt : iList) {
            List<InformationTag> itList = itMapper.selectTagByITMId(imt.getId());
            imt.setTagList(itList);
            if (userId != null && userId != 0){
                GiveLike gl = giveLikeMapper.searchByUserId(imt.getId(),userId);
                if (gl != null) imt.setIsLike(1); //已点赞
                else imt.setIsLike(0); //未点赞
            } else imt.setIsLike(0);
        }
        iPage.setRecords(iList);
        return iPage;
    }

    /**
     * 提交资讯
     * @param im 资讯实体对象
     * @return ResultMsg
     */
    @Override
    @Transactional
    public ResultMsg addInformation(Information im) {
        im.setCreateTime(Comm.getNow());
        im.setCheckStatus(0);
        im.setStatus(0);
        boolean save = this.save(im);
        String tagIds = im.getTypeTag();//标签id字符串
        String[] std = tagIds.split(";");
        List<InformationTagMiddle> middleList = new ArrayList<>();//创建资讯/资讯标签中间表集合
        for (String t : std) {
            InformationTagMiddle itm = new InformationTagMiddle();
            itm.setInformationId(im.getId());
            itm.setTagId(Integer.parseInt(t));
            itm.setCreateTime(Comm.getNow());
            middleList.add(itm);
        }
        //插入中间表
        itmMapper.insertList(middleList);

        if (save){//创建审批记录
            Approve app = new Approve();
            app.setType(6);//类型：资讯
            app.setContentId(im.getId());
            app.setCheckId(im.getApproverId());
            app.setSupperId(0);
            app.setLowerId(0);
            //app.setCheckTime(Comm.getNow());
            app.setCheckStatus(0);
            app.setCreateTime(Comm.getNow());
            app.setStatus(0);
            approveMapper.insert(app);

            //创建抄送记录
            String copyIds = im.getCopyId();
            if (!StringUtils.isEmpty(copyIds)){
                List<CopyTo> cList = new ArrayList<>();
                String[] copyId = copyIds.split(";");
                for (String c : copyId) {
                    CopyTo ct = new CopyTo();
                    ct.setType(5);//资讯
                    ct.setContentId(im.getId());//内容id
                    ct.setUserId(Integer.parseInt(c));//抄送至用户的id
                    ct.setCreateTime(Comm.getNow());//创建时间
                    ct.setStatus(0);
                    cList.add(ct);
                }
                if (cList.size() > 0){
                    //copyToMapper.insertList(cList);
                    copyToMapper.insertListByNote(cList);
                }
            }
            return ResultMsg.INSERT_SUCCESS.setNewMsg("提交成功");
        }else return ResultMsg.UPDATE_ERROR.setNewMsg("提交失败,内部错误");
    }

    /**
     * 查询资讯详情
     * @param imId 资讯id
     * @param userId 用户id
     * @return Information
     */
    @Override
    @Transactional
    public Information selectDetailById(Integer imId, Integer userId) {
        Information im = informationMapper.selectDetailById(imId);
        String copyIds = im.getCopyId();
        if (StringUtils.isEmpty(copyIds)) return im;
        String[] sm = copyIds.split(";");
        List<Integer> idList = new ArrayList<>();
        for (String s : sm) {
            idList.add(Integer.parseInt(s));
        }
        List<InformationTag> itList = itMapper.selectTagByITMId(im.getId());
        im.setTagList(itList);
        List<User> userList = userMapper.selectBatchIds(idList);
        im.setCopyList(userList);
        if (userId != null && userId != 0){
            GiveLike gl = giveLikeMapper.searchByUserId(im.getId(),userId);
            if (gl != null) im.setIsLike(1); //已点赞
            else im.setIsLike(0); //未点赞
            Collect ct = collectMapper.selectCollectById(im.getId(),userId,1);
            if (ct != null) im.setIsCollect(1);//已收藏
            else im.setIsCollect(0);//未收藏
        } else{
            im.setIsLike(0);//未点赞
            im.setIsCollect(0);//未收藏
        }
        //修改浏览次数
        im.setBrowseNumber(im.getBrowseNumber()+1);
        im.setUpdateTime(Comm.getNow());
        informationMapper.updateById(im);
        return im;
    }

    /**
     * 待办分页查询我发起的资讯
     * @param userId 发起人id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return IPage
     */
    @Override
    public IPage<Information> selectSponsorByPage(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<Information> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("creator_id",userId);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<Information> page = new Page<>(pageNumber,pageSize);
        return informationMapper.selectPage(page,wrapper);
    }

    /**
     * 分页查询待处理/已处理资讯
     * @param userId 审批人id
     * @param type 类型：0未处理，1已处理
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return IPage
     */
    @Override
    public IPage<Information> selectPendingByPage(Integer userId, Integer type, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<Information> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).eq("approver_id",userId);
        if (type == 0) wrapper.eq("check_status",0).orderByDesc("create_time");//未处理
        else if (type == 1){//已处理
            if (!StringUtils.isEmpty(time)){
                String startTime = time + " 00:00:00";
                String endTime = time + " 23:59:59";
                wrapper.between("create_time",startTime,endTime);
            }
            wrapper.ne("check_status",0).
                    ne("check_status",3).orderByDesc("create_time");
        }
        Page<Information> page = new Page<>(pageNumber,pageSize);
        return informationMapper.selectPage(page,wrapper);
    }

    /**
     * 分页查询抄送至我的资讯
     * @param userId 用户id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param time 日期
     * @return IPage
     */
    @Override
    public IPage<Information> selectCopyToMeByPage(Integer userId, Integer pageNumber, Integer pageSize, String time) {
        QueryWrapper<CopyTo> cWrapper = new QueryWrapper<>();
        cWrapper.eq("status",0).eq("user_id",userId).eq("type",5);
        List<CopyTo> cList = copyToMapper.selectList(cWrapper);
        if (cList.isEmpty()) return null;
        List<Integer> idList = new ArrayList<>();
        for (CopyTo c : cList) {
            idList.add(c.getContentId());
        }
        QueryWrapper<Information> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).ne("check_status",3).in("id",idList);
        if (!StringUtils.isEmpty(time)){
            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            wrapper.between("create_time",startTime,endTime);
        }
        wrapper.orderByDesc("create_time");
        Page<Information> page = new Page<>(pageNumber,pageSize);
        return informationMapper.selectPage(page,wrapper);
    }

    /**
     * 处理审批资讯
     * @param imId 资讯ID
     * @param result 处理结果：1通过，2驳回
     * @return ResultMsg
     */
    @Override
    @Transactional
    public ResultMsg checkInformationById(Integer imId, Integer result) {
        Information im = informationMapper.selectById(imId);
        if (im.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("处理失败，资讯已处理或已撤销");
        im.setCheckStatus(result);
        im.setUpdateTime(Comm.getNow());
        im.setPublishTime(Comm.getNow());
        informationMapper.updateById(im);
        UpdateWrapper<Approve> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("check_time",Comm.getNow()).set("check_status",result).set("update_time",Comm.getNow()).
                eq("type",6).eq("content_id",imId);
        approveMapper.update(null,updateWrapper);
        //informationMapper.checkInformationById(imId,result);
        return ResultMsg.UPDATE_SUCCESS.setNewMsg("处理成功");
    }


    /**
     * 撤销提出但还未处理的资讯
     * @param imId 资讯id
     * @return ResultMsg
     */
    @Override
    public ResultMsg repealInformationById(Integer imId) {
        Information im = informationMapper.selectById(imId);
        if (im.getCheckStatus() != 0) return ResultMsg.UPDATE_ERROR.setNewMsg("撤销失败，该资讯已处理不能撤销");
        im.setCheckStatus(3);
        im.setUpdateTime(Comm.getNow());
        informationMapper.updateById(im);
        UpdateWrapper<Approve> wrapper = new UpdateWrapper<>();
        wrapper.set("check_time",Comm.getNow()).set("check_status",3).set("update_time",Comm.getNow()).
                eq("type",6).eq("content_id",imId);
        approveMapper.update(null,wrapper);
        return ResultMsg.UPDATE_SUCCESS.setNewMsg("撤销成功");
    }
}
